/*!
 @header IntegralRecordsViewController.m
 @author 周益
 @version 1.0.0 2013/02/22 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "IntegralRecordsViewController.h"
#import "Helper.h"
#import "RTLabel.h"
#import "Config.h"
#import "IntegralRecordsDetailViewController.h"
#import "MJRefresh.h"

//  -业务逻辑细节说明-
//
//  @abstract       IntegralRecordsViewController为BaseRefreshViewController子类，支持下拉刷新和加载更多。
//                      在viewDidLoad时，会向服务器请求积分数据。

//  @discussion
//
//

//  @notes


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

#define LABEL_TEMPLATE @"<font color='gray'>数量：</font><font color='#fd6c01'>%d分</font><br><font color='gray'>原由：%@</font>"

@interface IntegralRecordsViewController ()<MJRefreshBaseViewDelegate>

@end

@implementation IntegralRecordsViewController
{
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.view.backgroundColor = [UIColor whiteColor];
    _blankPage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 832.0f/2.0f)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
//    [self integralRequestByCheckId:nil];
    
    _integralDataSource = [NSMutableArray new];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _integralDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        //日期
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.0f, 5.0f, 200.0f, 20.0f)];
        
        dateLabel.text = @"";
        dateLabel.font = _SYS_FONT_007;
        dateLabel.textColor = _SYS_COLOR_002;
        
        [cell.contentView addSubview:dateLabel];
        
        
        //积分记录类型
        UIImageView *integralImageView = [[UIImageView alloc] initWithFrame:CGRectMake(dateLabel.frame.origin.x + dateLabel.frame.size.width, 9.0f, 29.0f, 13.0f)];
        
        [cell.contentView addSubview:integralImageView];
        
        //积分数和原由描述
        RTLabel *label = [[RTLabel alloc] initWithFrame:CGRectMake(5.0f, dateLabel.frame.origin.y + dateLabel.frame.size.height + 5.0f, 280.0f, 50.0f)];
        
        label.font = _SYS_FONT_007;
        label.text = [NSString stringWithFormat:LABEL_TEMPLATE, 50, @""];
        
        [cell.contentView addSubview:label];
    }
    
    //获得次cell应该被填充的数据
    NSDictionary *dataForCell = [_integralDataSource objectAtIndex:indexPath.row];
    
    //获得cell的子views
    NSArray *views = [cell.contentView subviews];
    
    //设置日期
    UILabel *dateLabel = [views objectAtIndex:0];
    dateLabel.text = [dataForCell objectForKey:@"createTime"];
    
    //积分记录类型
    UIImageView *integralImageView = [views objectAtIndex:1];
    
    //根据action判断图标显示增加还是减少
    int action = [[dataForCell valueForKey:@"action"] integerValue];
    
    if (action == 0) {
        integralImageView.image = [UIImage imageNamed:@"more_icon_005"];
    }else{
        integralImageView.image = [UIImage imageNamed:@"more_icon_004"];
    }
    
    //设置数量和原由
    RTLabel *label = [views objectAtIndex:2];
    label.text = [NSString stringWithFormat:LABEL_TEMPLATE, [[dataForCell objectForKey:@"points"] integerValue], [dataForCell objectForKey:@"originally"]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    IntegralRecordsDetailViewController *integralRecordsDetailVC = [[IntegralRecordsDetailViewController alloc] initWithStyle:UITableViewStylePlain];
    integralRecordsDetailVC.record = [_integralDataSource objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:integralRecordsDetailVC animated:YES];
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*!
 @abstract 加载更多按钮事件
 @discussion 重写并调用父类的方法，添加自定义的刷新方法
 */
//- (void)refreshButtonEvent:(id)sender
//{
//    [super refreshButtonEvent:sender];
//    
//    if (_integralDataSource.count == 0) {
//        
//        [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
//        
//        //设置成刷新模式为默认下拉刷新
//        _isFooterRefresh = NO;
//        self.disableBottomRefresh = YES;
//        
//        return;
//    }
//    
//    //获取此时数据源中最后一条记录的id
//    
//    NSString *checkId = [NSString stringWithFormat:@"%ld", [self catchTheLastDataSourceId]];
//    
//    //发送加载更多的请求,数据接受成功后，设置_reloading
//    [self integralRequestByCheckId:checkId];
//}

#pragma mark - 私有方法

/*!
 @abstract 通过checkid查询向服务器请求积分记录
 @param checkId 需要分页功能时，传入此id，即数据源中最后一条数据的ID
 */
- (void)integralRequestByCheckId:(NSInteger)checkId
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_SCORE_LIST];
    request.delegate = self;
//    request.hudOn = true;
//    request.hudTitle = _L(@"title_loading_01");
    
    //id不为空，说明用户在加载更多
    if(checkId != 0){
        
        [request setValue:@(checkId) forParameter:@"checkId"];
        [request setSuccessSelector:@selector(moreIntegralDidReceived:)];
    }
    
    [request asynchronous];
}

/*!
 @abstract 实现下拉刷新
 @discussion 重写并调用父类的方法，添加自定义的刷新方法
 */
//- (void)reloadTableViewDataSource{
//	
//    [super reloadTableViewDataSource];
//    [self integralRequestByCheckId:nil];
//}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (NSInteger)catchTheLastDataSourceId
{
    if (_integralDataSource.count != 0) {
        return [[[_integralDataSource objectAtIndex:(_integralDataSource.count - 1)] objectForKey:@"id"] integerValue];
    }
    
    return 0;
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self integralRequestByCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        [self integralRequestByCheckId:[self catchTheLastDataSourceId]];
        
    }
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_integralDataSource.count != 0) {
            [_integralDataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_integralDataSource addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = self.tableView;
        }
        
        if (_integralDataSource.count > 0) {
            self.tableView.tableFooterView.hidden = NO;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
//        //当为下拉刷新和初次进入时，应该对数据源进行格式化
//        if (!_isFooterRefresh) {
//            
//            if (_integralDataSource == nil) {
//                _integralDataSource = [[NSMutableArray alloc] init];
//                
//            }else{
//                
//                [_integralDataSource removeAllObjects];
//            }
//            
//            //下来刷新成功后，就将加载更多的按钮显示出来
//            self.disableBottomRefresh = NO;
//        }
//        
//        //加载更多后成功获取数据后，应先调用此方法，恢复到点击加载更多之前的页面状态
//        [super stopRefresh];
//        
//        //如果加载更多没有得到数据，那么就提示用户，并且暂时隐藏家在更多
//        //在有数据的情况，就添加到数据源
//        if ([[dict objectForKey:@"data"] count] == 0) {
//            
//            //如果是加载更多时出现空数据源，那么就提示用户
//            if (_isFooterRefresh) {
//                [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
//            }
//            
//            self.disableBottomRefresh = YES;
//            
//        }else{
//            
//            [_integralDataSource addObjectsFromArray:[dict objectForKey:@"data"]];
//            
//        }
//        
//        [self.tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
//    //设置成刷新模式为默认下拉刷新
//    _isFooterRefresh = NO;
//    
    //数据源为空，显示友好的空页面
    if (_integralDataSource.count == 0) {
        
        _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_006@2x" ofType:@"png"]];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_blankPage];
        
    }else{
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [_blankPage removeFromSuperview];
    }
}

- (void)moreIntegralDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            [_integralDataSource addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

@end
